package com.example.springevent.service;

import com.example.springevent.event.OrderCreatedEvent;
import com.example.springevent.event.TransactionalEvent;
import com.example.springevent.model.Order;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.UUID;

@Slf4j
@Service
@RequiredArgsConstructor
public class OrderService {
    
    private final ApplicationEventPublisher eventPublisher;
    
    public Order createOrder(Long userId, BigDecimal amount) {
        // 模拟订单创建逻辑
        Order order = new Order();
        order.setId(System.currentTimeMillis());
        order.setUserId(userId);
        order.setOrderNumber(UUID.randomUUID().toString().replace("-", "").substring(0, 10));
        order.setAmount(amount);
        order.setCreatedAt(LocalDateTime.now());
        order.setStatus("CREATED");
        
        log.info("创建订单: {}", order.getOrderNumber());
        
        // 发布订单创建事件
        eventPublisher.publishEvent(new OrderCreatedEvent(this, order));
        
        return order;
    }
    
    @Transactional
    public Order processOrderWithTransaction(Long userId, BigDecimal amount, boolean shouldFail) {
        // 模拟订单处理逻辑
        Order order = new Order();
        order.setId(System.currentTimeMillis());
        order.setUserId(userId);
        order.setOrderNumber(UUID.randomUUID().toString().replace("-", "").substring(0, 10));
        order.setAmount(amount);
        order.setCreatedAt(LocalDateTime.now());
        order.setStatus("PROCESSING");
        
        log.info("处理订单(事务内): {}", order.getOrderNumber());
        
        // 发布事务性事件
        eventPublisher.publishEvent(new TransactionalEvent(this, "PROCESS_ORDER", order.getId().toString()));
        
        if (shouldFail) {
            throw new RuntimeException("订单处理失败");
        }
        
        order.setStatus("COMPLETED");
        return order;
    }
}